<template>
  <!-- 分配角色弹框 -->
  <el-dialog title="分配角色" :visible.sync="dialogVisible" width="750px" :before-close="handleBeforeClose">
    <div>
      <!-- 筛选条件 -->
      <el-row class="filter">
        <el-col :span="12">
          <span>应用选择 </span>
          <el-select v-model="params.clientId" @change="handleChange">
            <el-option
              v-for="item in clientOptions"
              :key="item.name"
              :label="item.name"
              :value="item.clientId"
            />
          </el-select>
        </el-col>
        <el-col :span="12" align="right">
          <el-input
            v-model="params.searchValue"
            filterable
            class="search-input"
            placeholder="搜索角色名称"
            suffix-icon="el-icon-search"
          />
        </el-col>
      </el-row>

      <!-- 标签也 -->
      <el-tabs v-model="activeName" type="card" @tab-click="toggleTabs">
        <el-tab-pane label="全部角色" name="all" />
        <el-tab-pane label="已添加角色" name="add" />
      </el-tabs>

      <!-- 角色表格 -->
      <el-table
        v-show="activeName === 'all'"
        :data="roleData"
        style="width: 100%; margin-bottom: 20px;"
        row-key="roleId"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="roleCode" label="角色编号" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="remark" label="描述" />
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleDispatch(row)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 已添加角色 -->
      <zlst-table v-show="activeName === 'add'" :columns="columns" :data="roleInfo" stripe>
        <!-- <el-table-column slot="active" label="状态">
          <template slot-scope="{ row }">
            <el-tag type="success" v-if="row.active === '1'">正常</el-tag>
            <el-tag type="warning" v-else>禁用</el-tag>
          </template>
        </el-table-column> -->
      </zlst-table>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import zlstTable from '@/components/Table/index.vue'

import http from '@/api/server/http'

export default {
  components: {
    zlstTable
  },
  data() {
    return {
      dialogVisible: false,
      activeName: 'all',
      columns: [
        { prop: 'roleName', label: '角色名' }
        // { slot: 'active' }
        // { prop: '', label: '操作' }
      ],
      clientOptions: [], //
      roleData: [], // 全部角色数据
      roleInfo: [], // 已添加角色
      params: {
        clientId: '',
        searchValue: ''
      },
      userId: '', // 当前用户id
      userInfo: {}
    }
  },
  computed: {
    userName() { // 操作人名字
      return this.$userInfo.userRep && this.$userInfo.userRep.username
    },
    modifiedBy() { // 操作人id
      return this.$userInfo.userRep && this.$userInfo.userRep.id
    },
    headers() {
      return {
        Authorization: 'Bearer ' + this.$userInfo.token,
        realm: this.$userInfo.realm,
        clientId: 'iam-front'
      }
    }
  },
  async mounted() {
    await this.getClientsList()
    if (this.clientOptions.length) {
      this.params.clientId = this.clientOptions[0].clientId
      await this.getRoleList()
    }
  },
  methods: {
    // 获取全部角色列表
    async getRoleList() {
      console.log(this.$userInfo)
      try {
        const res = await http.get('getRoleList', {
          params: {
            active: '0',
            clientId: this.params.clientId,
            realm: this.$userInfo.realm
          },
          headers: this.headers
        })
        if (res.data.code === 0) {
          this.roleData = res.data.data
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 获取已添加的角色
    async getRoleInfo() {
      try {
        // let username = this.$userInfo.userRep.username
        const username = this.userInfo.username
        const res = await http.get('getUserRoleList', {
          params: {
            realm: this.$userInfo.realm,
            username
          },
          headers: this.headers
        })
        if (res.data.code === 0) {
          // this.clientOptions = res.data.data
          console.log(res.data)
          const { roleRep = [] } = res.data.data

          this.roleInfo = roleRep
          // if (userRep.length) {
          //   let cur = userRep[0]
          //   let { system_roles = [] } = cur.attributes
          //   this.roleInfo = system_roles
          // }
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 获取用户信息
    async getUserInfo() {
      const userId = this.userId
      if (!userId) return
      try {
        const res = await http.get('getUserInfoById', {
          params: {
            realm: this.$userInfo.realm,
            userId
          },
          headers: this.headers
        })
        if (res.data.code === 0) {
          this.userInfo = res.data.data
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 获取领域下的客户端
    async getClientsList() {
      try {
        const res = await http.get('getClients', { realm: this.$userInfo.realm })
        if (res.data.code === 0) {
          this.clientOptions = res.data.data
        }
      } catch (error) {
        console.log(error)
      }
    },

    async handleDispatch(row) {
      console.log(row)
      const system_roles = this.userInfo.attributes.system_roles || []
      system_roles.push(row.roleId)
      // let params = {
      //   ...this.userInfo,
      //   attributes: {
      //     ...this.userInfo.attributes,
      //     system_roles
      //   }
      // }
      const params = {
        realmId: this.$userInfo.realm,
        clientId: this.params.clientId,
        userId: this.userId,
        roleIds: system_roles
      }
      try {
        const res = await http.post('updateUserRole', params, {
          headers: this.headers
        })
        // let res = await http.post('updateUserInfo', params, {
        //   headers: this.headers
        // })
        if (res.data.code === 0) {
          this.$message.success('角色分配成功!')
          this.closeDialog()
        } else {
          this.$message.error(res.data.message)
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 打开弹窗
    async openDialog() {
      this.dialogVisible = true

      await this.getUserInfo()
      await this.getRoleInfo()
    },

    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
    },

    // dialog 关闭前回调
    handleBeforeClose(done) {
      this.activeName = 'all'
      this.userId = ''
      this.userInfo = {}
      this.clientOptions = []
      this.roleData = []
      this.roleInfo = []

      done()
    },

    // 切换标签页
    toggleTabs() {

    },

    //
    handleChange(val) {
      // console.log(val)
      this.getRoleList()
    },

    // 提交
    async handleSubmit() {
      this.formData.modifiedBy = this.modifiedBy

      try {
        const res = await this.removeBlackList(this.formData)
        if (res.data.resultCode !== 0) {
          this.$message.success('解除黑名单失败！')
          return
        }
        this.$message.success('已解除黑名单！')
        this.dialogVisible = false
        // 完成解除 更新列表数据
        this.$emit('finished', true)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .search-input {
  input{
    border: 0;
    border-radius: 0;
    border-bottom: 1px solid #DCDFE6;
  }
}

/deep/ .el-tabs__header {
  margin: 15px 0;
}
</style>
